package com.ygl.core.nacos.context;


import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.registry.NacosServiceRegistry;
import com.ygl.common.constant.DiscoveryConstant;
import com.ygl.core.context.CoreApplicationContextInitializer;
import com.ygl.core.context.CoreContextAware;
import com.ygl.core.nacos.decorator.NacosServiceRegistryDecorator;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Map;

/**
 * @Author yanggld
 * @Date 2019/12/6-15:01
 * @Description
 */
public class NacosApplicationContextInitializer extends CoreApplicationContextInitializer {

	public Object afterInitialization(ConfigurableApplicationContext configurableApplicationContext, Object bean, String beanName) {
		//  如果是产生默认的NacosServiceRegistry实例。则对该实例进行包装
		if (bean instanceof NacosServiceRegistry) {
			NacosServiceRegistry nacosServiceRegistry = (NacosServiceRegistry) bean;
			NacosDiscoveryProperties nacosDiscoveryProperties = configurableApplicationContext.getBean(NacosDiscoveryProperties.class);
			return new NacosServiceRegistryDecorator(nacosDiscoveryProperties, nacosServiceRegistry, configurableApplicationContext);
		} else if (bean instanceof NacosDiscoveryProperties) {
			// 服务注册发现，自动设置metadata
			ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();
			NacosDiscoveryProperties nacosDiscoveryProperties = (NacosDiscoveryProperties) bean;
			Map<String, String> metadata = nacosDiscoveryProperties.getMetadata();
			metadata.put(DiscoveryConstant.SPRING_APPLICATION_NAME, CoreContextAware.getApplicationName(environment));
		}
		return bean;
	}
}
